package com.uncp.comisiondeadmision.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import com.uncp.comisiondeadmision.util.entity.ECdp;

public class DCdp implements IDCdp {

	private EntityManagerFactory emf;
	private EntityManager em;

	public void setEmf(EntityManagerFactory emf) {
		this.emf = emf;
	}

	public ECdp buscarXPk(String cdp) throws Exception {

		em = emf.createEntityManager();
		ECdp cdpDto = null;
		try {
			cdpDto = em.find(ECdp.class, cdp);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			em.close();
		}
		return cdpDto;
	}

	public void insertarCDP(ECdp cdp) {

		em = emf.createEntityManager();

		try {
			em.getTransaction().begin();
			em.persist(cdp);

		} catch (Exception e) {
			e.printStackTrace();
			em.getTransaction().rollback();

		} finally {
			em.getTransaction().commit();
			em.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<ECdp> listarCDP() throws Exception {

		em = emf.createEntityManager();
		List<ECdp> lstEcdp = new ArrayList<ECdp>();

		try {

			Query query = em
					.createQuery("select eCdp from ECdp eCdp order by eCdp.postulante.int_cod_postu desc");

			lstEcdp = query.getResultList();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			em.close();
		}

		return lstEcdp;
	}

}
